from sqlalchemy import or_
from common.BaseHandler import BaseHandler
from common.Models import Author, Post, Category, Tag, PostCateMiddle, PostTagMiddle, PostViewHistory, Visitor, Comment


def get_post_category(self, post_id):
    cate = self.session.query(Category) \
                .join(PostCateMiddle, PostCateMiddle.category_id == Category.id) \
                .filter(PostCateMiddle.post_id == post_id).first()
    return cate


def get_post_tags(self, post_id):
    tags = self.session.query(Tag) \
                .join(PostTagMiddle, PostTagMiddle.tag_id == Tag.id) \
                .filter(PostTagMiddle.post_id == post_id).all()
    return tags


class PostIndexHandler(BaseHandler):
    def get(self):
        post_list, author, category_list, tag_list, post_count = [], None, [], [], 0
        data = self.get_params()
        cate_id = data.get("cate_id", None)
        tag_id = data.get("tag_id", None)
        search = data.get("search", None)
        try:
            # 作者
            author = self.session.query(Author).filter_by(is_delete=0).order_by(Author.create_time.asc()).first()
            # 分类
            category_list = self.session.query(Category).filter_by(is_delete=0).order_by(Category.create_time.desc()).all()
            for cate in category_list:
                cate.post_count = self.session.query(PostCateMiddle).filter_by(category_id=cate.id).count()
            # 标签
            tag_list = self.session.query(Tag).filter_by(is_delete=0).order_by(Tag.create_time.desc()).all()
            # 博文
            post_list = self.session.query(Post).filter_by(is_delete=0)
            post_count = post_list.count()
            if cate_id:
                post_list = post_list.join(PostCateMiddle, PostCateMiddle.post_id == Post.id).filter(PostCateMiddle.category_id == int(cate_id))
            if tag_id:
                post_list = post_list.join(PostTagMiddle, PostTagMiddle.post_id == Post.id).filter(PostTagMiddle.tag_id == int(tag_id))
            if search:
                post_list = post_list.filter(or_(Post.title.like(f"%{search}%"), Post.excerpt.like(f"%{search}%")))
            post_list = post_list.order_by(Post.create_time.desc()).all()

            for post in post_list:
                cate = get_post_category(self, post.id)
                tags = get_post_tags(self, post.id)
                post.category_name = cate.name if cate else "无"
                post.tag_names = [tag.name for tag in tags]
                post.author_name = self.session.query(Author).filter_by(id=post.author_id).first().name
        except Exception as e:
            self.logger.error(e)
        self.render("blog/index.html", post_list=post_list, author=author, category_list=category_list,
                    tag_list=tag_list, post_count=post_count, cate_id=int(cate_id) if cate_id else 0,
                    tag_id=int(tag_id) if tag_id else 0, search=search)


class PostDetailHandler(BaseHandler):
    def get(self, blog_id):
        try:
            post_obj = self.session.query(Post).filter_by(id=int(blog_id), is_delete=0).first()
            if post_obj:
                post_obj.views += 1     # 浏览数+1
                cate = get_post_category(self, post_obj.id)
                tags = get_post_tags(self, post_obj.id)
                blog_info = {
                    "id": post_obj.id,
                    "title": post_obj.title,
                    "author": self.session.query(Author).filter_by(id=post_obj.author_id).first().name,
                    "time": str(post_obj.create_time),
                    "views": post_obj.views,
                    "category": cate.name if cate else "无",
                    "tags": [tag.name for tag in tags],
                    "content": post_obj.body,
                    "comments": self.session.query(Comment).filter_by(post_id=post_obj.id, is_delete=0).count()
                }
                # 浏览记录
                new_views = PostViewHistory(nick_name="游客", post_id=post_obj.id,
                                            ip_address=self.request.headers.get("X-Real-IP", self.request.remote_ip))
                self.session.add(new_views)
                self.session.commit()
                comment_list = []
                comments = self.session.query(Comment.content, Comment.create_time, Visitor.nick_name) \
                                .filter_by(post_id=post_obj.id, is_delete=0) \
                                .join(Visitor, Visitor.id == Comment.visitor_id) \
                                .order_by(Comment.create_time.desc()) \
                                .all()
                for c in comments:
                    comment_list.append({
                        "name": c[2],
                        "content": c[0],
                        "create_time": c[1],
                    })
                self.render("blog/detail.html", blog_info=blog_info, comment_list=comment_list)
            else:
                self.write_error(404)
        except Exception as e:
            self.session.rollback()
            self.logger.error(e)


